package com.hyq.market.utils;

import android.text.TextUtils;

import com.hyq.market.api.Constant;
import com.hyq.market.base.NetCallback;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Administrator on 2017/7/30 0030.
 */

public class HttpConnetionUtil {
    private static String CHARSET_UTF8="utf-8";


    public static void login(String username, String password, org.xutils.common.Callback.CommonCallback<String> responseCallbackHandler) {
                 Map<String, String> params = new HashMap<>();
                 params.put("username", username);
                 params.put("password", password);
                 post("https:/..../login", params, responseCallbackHandler);
             }


    public static void post(final String url, Map<String, String> _params, final org.xutils.common.Callback.CommonCallback<String> responseCallbackHandler) {

//        if (!NetworkUtils.isNetworkConnected(RunnerApp.getContext())) {
//            if (responseCallbackHandler != null) {
//                responseCallbackHandler.onNetworkError();
//                responseCallbackHandler.onFinish();
//            }
//            return;
//        }
        final String params = map2Url(_params);
        new Thread(new Runnable() {
            @Override
            public void run() {
                post(url, params, responseCallbackHandler);
            }
        }).start();
    }

    /**
     * map转url参数
     */
    public static String map2Url(Map<String, String> paramToMap) {
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url    = new StringBuffer();
        boolean      isfist = true;
        for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue();
            if (!TextUtils.isEmpty(value)) {
                try {
                    url.append(URLEncoder.encode(value, CHARSET_UTF8));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return url.toString();
    }


    /**
     * post请求
     */
    public static void post(String url, String params, org.xutils.common.Callback.CommonCallback<String> responseCallbackHandler) {
        StringBuffer bufferRes = null;
        try {
            HttpURLConnection http = initHttps(url, "POST", null);
            OutputStream out = http.getOutputStream();
            out.write(params.getBytes(CHARSET_UTF8));
            out.flush();
            out.close();
            getCookie(http);
            InputStream in = http.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8));
            String valueString = null;
            bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            in.close();
            if (http != null) {
                http.disconnect();// 关闭连接
            }
            if(responseCallbackHandler != null) {
                responseCallbackHandler.onSuccess(bufferRes.toString());
//                LogUtils.d(tag, "onSuccess");
//                LogUtils.d(tag, "onSuccess:" + bufferRes.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (responseCallbackHandler != null) {
                responseCallbackHandler.onError(e,false);
            }
        }
//        if (responseCallbackHandler != null) {
//            responseCallbackHandler.onFinish();
//        }
    }


    /**
     * 初始化http请求参数
     */
    private static HttpURLConnection initHttps(String url, String method, Map<String, String> headers)
            throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
//        TrustManager[] tm = {new CustomX509TrustManager()};
//        SSLContext sslContext = SSLContext.getInstance("TLSv1");
//        sslContext.init(null, tm, new java.security.SecureRandom());
//        // 从上述SSLContext对象中得到SSLSocketFactory对象
//        SSLSocketFactory ssf  = sslContext.getSocketFactory();
        URL _url = new URL(url);
        HttpURLConnection http = (HttpURLConnection) _url.openConnection();
        // 连接超时
        http.setConnectTimeout(25000);
        // 读取超时 --服务器响应比较慢，增大时间
        http.setReadTimeout(25000);
        http.setRequestMethod(method);
            http.setRequestProperty("Origin","http://m.wzhj365.com");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        http.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36");
        http.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");
        if (null != headers && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                http.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
//        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        return http;
    }

    private static String getCookie(HttpURLConnection  conn){
        String sessionId = "";
        String cookieVal = "";
        String key = null;
        //取cookie
        for(int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++){
            if(key.equalsIgnoreCase("set-cookie")){
                cookieVal = conn.getHeaderField(i);
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                sessionId = sessionId + cookieVal + ";";
            }
        }
        Constant.LoginCookie=sessionId;
        return sessionId;
    }

    // 证书管理
    class CustomX509TrustManager implements X509TrustManager {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }
}
